from urllib import urlopen

## TODO: Ask tharis to comment this file


class Magazine():

    def __init__(self, to_find):
        self.to_find = to_find
        self.link = "http://www.revista-programar.info/front/articles/"
        self.source = urlopen(self.link).read()
        self.articles = []
        self.found = []

        self.filter()
        self.find_articles()
        self.find_article()

        f=file("cache.mag", 'w')

        for i in self.found:
            f.write(i[0] + '\n' + i[1] + '\n')

    def filter(self):
        for i in range(0, len(self.source)):
            TharisNeverComments = self.source[i:i+len("<div id=\"content\">")]
            if TharisNeverComments == "<div id=\"content\">":
                self.source = self.source[i:]

    def find_articles(self):
        for i in range(0, len(self.source)):
            if self.source[i:i+len("<a href=")] == "<a href=":
                matter = ""
                for j in range(0, 100):
                    if matter[-4:] == "</a>":
                        self.articles.append(matter)
                        break
                    else:
                        matter+=self.source[i+j]

    def find_article(self):
        found = []
        for i in self.articles:
            title = i.split('>')[1][0:-3]
            url = self.link.replace('/front/articles/', i.split('"', 2)[1])
            if self.to_find.lower() in title.lower():
                found.append((title, url))

        self.found = found
